package com.xuecheng.content.controller;

import com.xuecheng.commons.model.vo.CoursePubVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.domain.CoursePub;
import com.xuecheng.content.service.CoursePubService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程发布前端控制器
 * </p>
 *
 * @author itheima
 */
@Slf4j
@RestController
@RequestMapping("/coursePub")
public class CoursePubController {

    @Autowired
    private CoursePubService  coursePubService;

    /**
     * 课程预览
     * 请求地址GET ：/preview/{courseBaseId}
     * 参数：课程ID
     * 返回值：
     *   ModelAndView （数据和页面模型）
     *      数据：map
     */
    @GetMapping("/preview/{courseBaseId}")
    public ModelAndView preview(@PathVariable("courseBaseId") Long courseBaseId) {
        ModelAndView mv = new ModelAndView();
        //指定模板
        mv.setViewName("learing_article");
        //指定数据
        //调用service，查询页面所需要的的预览数据
        Map<String,Object> map = coursePubService.preview(courseBaseId);
        mv.addAllObjects(map);
        return mv;
    }

    /**
     * 课程发布
     *  Post  /publish/{courseBaseId}
     */
    @PostMapping("/publish/{courseBaseId}")
    public ResponseResult publish(@PathVariable("courseBaseId") Long courseBaseId)
            throws Exception {
        return coursePubService.publish(courseBaseId);
    }

    /**
     * 查询所有已经发布的课程
     * 地址： GET /findAll
     * 返回值：ResponseResult<List<CoursePubVo>>
     */
    @GetMapping("/findAll")
    public ResponseResult<List<CoursePubVo>> findAll() {
        //调用service查询所有：List<CoursePub>
        List<CoursePub> list = coursePubService.list();
        //转化返回值
        List<CoursePubVo> vos = BeanHelper.copyWithCollection(list, CoursePubVo.class);
        //返回
        return ResponseResult.okResult(vos);
    }

    /**
     * 根据id查询课程发布对象
     */
    @GetMapping("/{id}")
    public ResponseResult<CoursePubVo> findById(@PathVariable("id") Long id) {
        CoursePub coursePub = coursePubService.getById(id);
        CoursePubVo vo = BeanHelper.copyProperties(coursePub, CoursePubVo.class);
        return ResponseResult.okResult(vo);
    }
}
